import re

from PySide2 import QtCore
from PySide2.QtWidgets import QVBoxLayout
import share
from elementUI.h5_element import WebEngineView


class bind:
    xy = {"rowIndex": -1, "columnIndex": -1}
    xyj = {"rowIndex": -1, "columnIndex": -1, "value": 0}

    def __init__(self):
        self.ui = share.SI.main.ui

    def back(self):
        # 绑定返回按钮
        self.ui.stackedWidget.setCurrentIndex(0)

    # 初始化源数据体表格
    def initialize(self, url):
        try:
            self.ui.webbrowser.load(QtCore.QUrl(url))
        except Exception as e:
            vLayout = QVBoxLayout()
            webbrowser = WebEngineView()
            webbrowser.load(QtCore.QUrl(url))
            self.ui.webbrowser = webbrowser
            vLayout.addWidget(webbrowser)
            vLayout.setContentsMargins(5, 2, 5, 2)
            self.ui.original_widget.setLayout(vLayout)

        self.ui.stackedWidget.setCurrentIndex(1)

    # 单元格单击事件
    def item_alter(self):
        if self.xyj['columnIndex'] != -1 and self.examine(self.xyj['columnIndex']) == 0:
            self.ui.original_tableView.model().setData(
                self.ui.original_tableView.model().index(self.xyj['rowIndex'], self.xyj['columnIndex']),
                self.xyj['value'])
            # 查询当前选中单元格行列
            rowIndex = self.ui.original_tableView.currentIndex().row();
            columnIndex = self.ui.original_tableView.currentIndex().column();
            # 更新选中值
            self.xyj['rowIndex'], self.xyj['columnIndex'], self.xyj[
                'value'] = rowIndex, columnIndex, self.ui.original_tableView.model().item(rowIndex, columnIndex).text()
        elif self.xyj['columnIndex'] == -1:
            # 查询当前选中单元格行列
            rowIndex = self.ui.original_tableView.currentIndex().row();
            columnIndex = self.ui.original_tableView.currentIndex().column();
            # 更新选中值
            self.xyj['rowIndex'], self.xyj['columnIndex'], self.xyj[
                'value'] = rowIndex, columnIndex, self.ui.original_tableView.model().item(rowIndex, columnIndex).text()

        self.flag = 0
        # 查询上次选中单元格值
        if self.xy['rowIndex'] != -1:
            rowIndex = self.xy['rowIndex']
            columnIndex = self.xy['columnIndex']
            text = self.ui.original_tableView.model().item(rowIndex, columnIndex).text()

            # 判断当前修改数是（借方，贷方）还是修改数
            role = self.examine(columnIndex)
            if role == 0:
                self.xy['rowIndex'] = -1
                return  # 是报表数，直接返回不做记录

            # 获取调整数或借贷数
            adjusted_figures = self.ui.original_tableView.model().item(rowIndex, columnIndex + role).text()
            # 调整数或借贷数为空字符串预处理
            if adjusted_figures == '': adjusted_figures = 0
            if text == '': text = 0
            # 转换数据格式
            coordination = float(adjusted_figures.replace(',', '')) if isinstance(adjusted_figures,
                                                                                  str) else adjusted_figures
            text = float(text.replace(',', '')) if isinstance(text, str) and self.is_number(
                text.replace(',', '')) else text
            try:
                # 开始计算实际的报表数
                report_date = self.formatNum(text + coordination)
                # 更改报表数
                if role == 1:  # 借贷数
                    self.ui.original_tableView.model().setData(
                        self.ui.original_tableView.model().index(rowIndex, columnIndex + 2), report_date)
                else:  # 报表数
                    self.ui.original_tableView.model().setData(
                        self.ui.original_tableView.model().index(rowIndex, columnIndex + 1), report_date)

                # 存储行号
                self.processing_dataList.append(rowIndex)
            except:
                pass

        # 查询当前选中单元格行列
        rowIndex = self.ui.original_tableView.currentIndex().row();
        columnIndex = self.ui.original_tableView.currentIndex().column();

        # 更新选中值
        self.xy['rowIndex'], self.xy['columnIndex'] = rowIndex, columnIndex

    # 判断字符串是否是数字
    def is_number(self, target_str):
        try:
            float(target_str)
            return True
        except:
            pass
        if target_str.isnumeric():
            return True
        return False

    # 数字变千分数
    def formatNum(self, num):
        num = "%.2f" % num
        num = str(num)
        pattern = r'(\d+)(\d{3})((,\d{3})*)'
        while True:
            num, count = re.subn(pattern, r'\1,\2\3', num)
            if count == 0:
                break
        return num

    # 判断当前修改数是（解放，贷方）还是修改数  0为（借放，贷方）   1为调整数   2为报表数
    def examine(self, columnIndex):
        item = self.ui.original_tableView.model().item(1, columnIndex).text()
        if item == '调整数':
            return -1
        else:
            return 0
